package com.hmdp.utils;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

@Component
public class RedisIdWorker {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    private final static long BEGIN_TIMESTAMP = 1735689600;
    private final static long COUNT_BITS = 32;

    //生成64位全局唯一ID，使用redis的incr函数生成，可保证全局唯一性
    //传入业务的key头，确保是针对每一个模块生成的id
    public long nextId(String keyPrefix){
        //1.生成时间戳
        LocalDateTime now = LocalDateTime.now();
        long epochSecond = now.toEpochSecond(ZoneOffset.UTC);
        long timestamp = epochSecond - BEGIN_TIMESTAMP;

        //2.生成序列号
        //2.1获取当前日期，精确到天，保证序列号内容不超过32位（redis最高位是64）
        String date = now.format(DateTimeFormatter.ofPattern("yyyyMMdd"));

        //2.2自增长
        long count = (long) stringRedisTemplate.opsForValue().increment("icr" + keyPrefix + ":" + date);

        //3.拼接
        return timestamp << COUNT_BITS | count;
    }

}
